package ext.tianma.part.processors;

import java.util.List;
import java.util.Locale;

import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.part.WTPart;
import wt.query.ClassAttribute;
import wt.query.OrderBy;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.LocalizableMessage;
import wt.util.WTContext;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTProperties;
import wt.workflow.definer.WfProcessTemplate;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfEngineServerHelper;
import wt.workflow.engine.WfProcess;

import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

public class PartProcessor extends DefaultObjectFormProcessor{
	 	private static WTContext wtcontext = WTContext.getContext();
	    private static boolean VERBOSE = false;
	    private static String CLASSNAME = PartProcessor.class.getName();
	    private static final String RESOURCE = "ext.tianma.part.resource.partResource";
	    private static Locale LOCALE = null;


	    static
	    {
	        try
	        {
	            WTProperties wtproperties = WTProperties.getLocalProperties();
	            VERBOSE = wtproperties.getProperty("ext.generic.print.verbose", false);
	            LOCALE = wtcontext.getLocale();
	        }
	        catch (Throwable throwable)
	        {
	            throwable.printStackTrace(System.err);
	            throw new ExceptionInInitializerError(throwable);
	        }
	    }

	    public PartProcessor()
	    {
	    }
		/* * 启动版本进阶流程
		 * @param pbo 主要业务对象
		 * @throws QueryException
		 * @throws WTException
		 * @throws WTPropertyVetoException
		 */
	    public FormResult doOperation(NmCommandBean nmcommandbean, List list) throws WTException
	    {
	        if (VERBOSE)
	        {
	            System.out.println(">>>>" + CLASSNAME + ".doOperation()");
	        }
	        FormResult formresult = new FormResult(FormProcessingStatus.SUCCESS);
	        FormResult formresult1 = new FormResult(FormProcessingStatus.SUCCESS);

	        NmOid actionOid = nmcommandbean.getActionOid();
	        WTPart pbo = (WTPart) ObjectReference.newObjectReference(actionOid.getOid()).getObject();
	        try
	        {
	            if(pbo!=null){
	            	QuerySpec querysearch = null;
	    			QueryResult queryresult = null;
	    			querysearch = new QuerySpec(WfProcessTemplate.class);
	    			SearchCondition sc = new SearchCondition(WfProcessTemplate.class, "name", SearchCondition.EQUAL, "样品承认及批准流程");
	    			querysearch.appendWhere(sc);
	    			OrderBy orderby = new OrderBy(new ClassAttribute(WfProcessTemplate.class, "thePersistInfo.createStamp"), true); // true为降序，false为升序
	    			querysearch.appendOrderBy(orderby, 0);

	    			queryresult = PersistenceHelper.manager.find(querysearch);
	    			WfProcessTemplate wfprocesstemplate = null;
	    			
	    			if (queryresult.hasMoreElements()) {
	    				wfprocesstemplate = (WfProcessTemplate) queryresult.nextElement();                                        //获取流程模板
	    				System.out.println("Debug  样品承认及批准流程："+wfprocesstemplate.getName());
	    				WTPrincipal wtprincipal = SessionHelper.manager.getPrincipal();
	    				String processName = "样品承认及批准流程_"+pbo.getNumber();
	    				System.out.println("Debug  样品承认及批准流程："+wtprincipal.getName());
	    				WTPrincipalReference wtprincipalreference = WTPrincipalReference.newWTPrincipalReference(wtprincipal);
	    				boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
	    				try {
	    					
	    					WfProcess wfprocess = WfEngineHelper.service.createProcess(wfprocesstemplate, pbo.getLifeCycleTemplate(),pbo.getContainerReference());
	    					WfEngineServerHelper.service.setPrimaryBusinessObject(wfprocess,pbo);
	    					wfprocess.setName(processName);
	    		    		ProcessData processdata = wfprocess.getContext();
	    		    		wfprocess.setCreator(wtprincipalreference);
	    		    		wfprocess = (WfProcess)PersistenceHelper.manager.save(wfprocess);	
	    		    		wfprocess.start(processdata, true, pbo.getContainerReference());
	    				} 

	    				finally {
	    					SessionServerHelper.manager.setAccessEnforced(flag);
	    				}
	    			}
	            }
	        }
	        catch (Exception e)
	        {
	            formresult.setStatus(FormProcessingStatus.FAILURE);
	            formresult.addFeedbackMessage(new FeedbackMessage(FeedbackType.FAILURE, LOCALE, new WTMessage(RESOURCE, "TITLE_INFO", null), null, new LocalizableMessage[]
	                        { new WTMessage(RESOURCE, "TASK_SUBMIT_ERROR", null) }));
	            e.printStackTrace();
	        }

	        formresult1 = super.doOperation(nmcommandbean, list);
	        formresult = mergeIntermediateResult(formresult, formresult1);
	        if (VERBOSE)
	        {
	            System.out.println("<<<<" + CLASSNAME + ".doOperation()");
	        }
	        if (formresult.getStatus().equals(FormProcessingStatus.SUCCESS))
	        {
	            formresult.addFeedbackMessage(new FeedbackMessage(FeedbackType.SUCCESS, LOCALE, new WTMessage(RESOURCE, "TASK_SUBMIT_OK", null), null, new LocalizableMessage[]
	                        { new WTMessage(RESOURCE, "TASK_SUBMIT_OK", null) }));
	        }

	        return formresult;
	    }
	
}
